package com.woniu.user.service.impl;

import com.woniu.entity.Result;
import com.woniu.user.mapper.UserMapper;
import com.woniu.user.pojo.Comment;
import com.woniu.user.mapper.CommentMapper;
import com.woniu.user.pojo.User;
import com.woniu.user.pojo.dto.CommentDTO;
import com.woniu.user.pojo.dto.CommentMessage;
import com.woniu.user.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.user.util.SMSUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 评论表 服务实现类
 * </p>
 *
 * @author LiFangyu
 * @since 2023-02-15
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    @Autowired(required = false)
    private CommentMapper commentMapper;

    @Autowired(required = false)
    private UserMapper userMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public Result addComment(CommentDTO commentDTO) {
        //添加一条评论
        Comment comment = new Comment();
        comment.setUserId(commentDTO.getUserId());
        comment.setArticleId(commentDTO.getArticleId());
        comment.setContent(commentDTO.getContent());
        comment.setReplyTo(commentDTO.getReplyTo());
        int insert = commentMapper.insert(comment);
        if (insert > 0) {
            //回复评论给用户发通知
            if (commentDTO.getReplyTo() != null){
                //mq消息队列通知
                CommentMessage commentMessage = new CommentMessage();
                commentMessage.setUserId(commentDTO.getReplyUserId());
                commentMessage.setMessage(commentDTO.getContent());
                rabbitTemplate.convertAndSend("config_exchange", "comment", commentMessage);

                //短信通知
                User user = userMapper.selectById(commentDTO.getReplyUserId());
//                SMSUtils.sendSms();
            }
            return Result.ok();
        }
        return Result.error(200,"评论失败");
    }

    @Override
    public Result getComment(String articleId) {
        List<Comment> commentList =  commentMapper.selectListComment(articleId);
        return Result.ok(commentList);
    }
}
